package azydbly.util;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * @ClassName: PdfUtils
 * @Description: 生成pdf工具类
 * @Author: azydbly
 * @CreateDate: 2021/5/19 08:13
 */
public class PdfUtils {

	/**
	 * 利用模板生成pdf
	 * @param o
	 * @param templatePath  模版路径
	 * @param newPDFPath 	生成之后的路径
	 * @param pageNumber	需要截取PDF的页数，如果为小于1的值则获取生成模版的全部页数，如只需要模版的前两页则传2
	 */
	public static void pdfOut(Map<String, Object> o, String templatePath, String newPDFPath, Integer pageNumber) {
		PdfReader reader;
		FileOutputStream out;
		ByteArrayOutputStream bos;
		PdfStamper stamper;
		try {
			BaseFont bf = BaseFont.createFont("temp/fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			Font FontChinese = new Font(bf, 5, java.awt.Font.BOLD);
			// 输出流
			out = new FileOutputStream(newPDFPath);
			// 读取pdf模板
			reader = new PdfReader(templatePath);
			bos = new ByteArrayOutputStream();
			stamper = new PdfStamper(reader, bos);
			AcroFields form = stamper.getAcroFields();
			//文字类的内容处理
			Map<String, String> dateMap = (Map<String, String>) o.get("dateMap");
			form.addSubstitutionFont(bf);
			for (String key : dateMap.keySet()) {
				String value = dateMap.get(key);
				form.setField(key, value);
			}
			//图片类的内容处理
			Map<String, String> imgMap = (Map<String, String>) o.get("imgMap");
			if (imgMap != null) {
				for (String key : imgMap.keySet()) {
					String value = imgMap.get(key);
					String imgpath = value;
					if (form.getFieldPositions(key) != null) {
						int pageNo = form.getFieldPositions(key).get(0).page;
						Rectangle signRect = form.getFieldPositions(key).get(0).position;
						float x = signRect.getLeft();
						float y = signRect.getBottom();
						//根据路径读取图片
						Image image = Image.getInstance(imgpath);
						//获取图片页面
						PdfContentByte under = stamper.getOverContent(pageNo);
						//图片大小自适应
						image.scaleToFit(signRect.getWidth(), signRect.getHeight());
						//添加图片
						image.setAbsolutePosition(x, y);
						under.addImage(image);
					}
				}
			}
			// 如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
			stamper.setFormFlattening(true);
			stamper.close();
			Document doc = new Document();
			PdfCopy copy = new PdfCopy(doc, out);
			doc.open();

			if (pageNumber == null || pageNumber < 1 || pageNumber > reader.getNumberOfPages()) {
				pageNumber = reader.getNumberOfPages();
			}
			for (int i = 1; i < pageNumber + 1; i++) {
				PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
				copy.addPage(importPage);
			}
			doc.close();
		} catch (IOException e) {
			System.out.println(e);
		} catch (DocumentException e) {
			System.out.println(e);
		}
	}
}
